import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:wechat/const.dart';
import 'package:wechat/pages/chat/search_cell.dart';
import 'package:wechat/tools/http_manager.dart';

class Chat {
  final String? name;
  final String? message;
  final String? imageUrl;
  Chat({this.name, this.message, this.imageUrl});

  factory Chat.formMap(Map map) {
    return Chat(
      name: map['name'],
      message: map['message'],
      imageUrl: map['imageUrl'],
    );
  }
}

class ChatPage extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}

func(message) {
  print('开始');
  for (int i = 0; i < 10000000000; i++) {}
  print('结束了！');
}

class _ChatPageState extends State<ChatPage>
    with AutomaticKeepAliveClientMixin<ChatPage> {
  // Timer _timer;
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  bool _cancelConnect = false;
  //模型数组
  List<Chat> _datas = [];
  @override
  // void dispose() {
  //   // TODO: implement dispose
  //   super.dispose();
  //   if (_timer != null && _timer.isActive) {
  //     _timer.cancel();
  //   }
  // }

  @override
  void initState() {
    super.initState();

    // int _count = 0;
    // _timer = Timer.periodic(Duration(seconds: 1), (timer) {
    //   _count++;
    //   print(_count);
    //   if (_count == 99) {
    //     timer.cancel();
    //   }
    // });

    //获取网络数据
    getDatas()
        .then((List<Chat> datas) {
          if (!_cancelConnect) {
            setState(() {
              _datas = datas;
            });
          }
        })
        .catchError((e) {
          _cancelConnect = true;
          print(e);
        })
        .whenComplete(() {
          print('完毕！');
        })
        .timeout(Duration(seconds: 6))
        .catchError((timeout) {
          print('超时了！$timeout');
          _cancelConnect = true;
        });
  }

  Future<List<Chat>> getDatas() async {
    _cancelConnect = false;
    //发送请求
    final response = await HttpManager.get(
        'http://rap2api.taobao.org/app/mock/256798/api/chat/list');
    if (response.statusCode == 200) {
      //map 作为List的遍历方法。
      List<Chat> chatList = response.data['chat_list']
          .map<Chat>((item) => Chat.formMap(item))
          .toList();
      return chatList;
    } else {
      throw Exception('statusCode:${response.statusCode}');
    }
  }

  Widget _buildPopupMenuItem(String imgAss, String title) {
    return Row(
      children: [
        Image(
          image: AssetImage(imgAss),
          width: 20,
        ),
        SizedBox(
          width: 20,
        ),
        Text(
          title,
          style: TextStyle(color: Colors.white),
        ),
      ],
    );
  }

  Widget _tiemBuilderForRow(BuildContext context, int index) {
    if (index == 0) {
      return SearchCell(_datas);
    }
    //保证后面的数据正确。
    index--;
    return ListTile(
      title: Text(_datas[index].name ?? ''),
      subtitle: Container(
        alignment: Alignment.bottomCenter,
        padding: EdgeInsets.only(
          right: 10,
        ),
        height: 25,
        child: Text(
          _datas[index].message ?? '',
          overflow: TextOverflow.ellipsis,
        ),
      ),
      leading: Container(
        width: 44,
        height: 44,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6.0),
            image:
                DecorationImage(image: NetworkImage(_datas[index].imageUrl ?? ''))),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: WeChatThemeColor,
        title: Text('微信页面'),
        centerTitle: true,
        actions: [
          Container(
            margin: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              color: Color.fromRGBO(1, 1, 1, 0.65),
              offset: Offset(0, 60.0),
              child: Image(
                image: AssetImage('images/圆加.png'),
                width: 25,
              ),
              itemBuilder: (BuildContext context) {
                return <PopupMenuItem<String>>[
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/发起群聊.png', '发起群聊')),
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/添加朋友.png', '添加朋友')),
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/扫一扫1.png', '扫一扫')),
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/收付款.png', '收付款')),
                ];
              },
            ),
          ),
          GestureDetector(
            onTap: () {
              compute(func, 123);
            },
            child: Container(
              child: Icon(Icons.add),
            ),
          )
        ],
      ),
      body: Container(
        child: Container(
          child: _datas.length == 0
              ? Center(
                  child: Text('Loading...'),
                )
              : ListView.builder(
                  itemCount: _datas.length + 1,
                  itemBuilder: _tiemBuilderForRow,
                ),
        ),
      ),
    );
  }
}
